//
//  ZKeyChain.m
//  NewProject
//
//  Created by 陈洪鑫 on 2018/8/1.
//  Copyright © 2018年 chenIos. All rights reserved.
//

#import "ZKeyChain.h"
#import <Security/Security.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#define Z_SECRET_KEY @"m#@!&^%$)(_+~>cccml~':23249mk*"
#define Z_SECRET_KEY_TWO @"^($%^&#@!mMkKL:/?fdfd=2\"344';"
@implementation ZKeyChain
+ (BOOL)addPrivate:(NSString *)Private forKey:(NSString *)key{
    key = [@"z_key_chain_chenhongxin_private:" stringByAppendingString:key];
    return [self addKeychainData:Private forKey:key];
}
+ (NSString *)getPrivateForKey:(NSString *)key{
    key = [@"z_key_chain_chenhongxin_private:" stringByAppendingString:key];
    return [self getKeychainDataForKey:key];
}
+ (BOOL)deletePrivateForKey:(NSString *)key{
    key = [@"z_key_chain_chenhongxin_private:" stringByAppendingString:key];
   return  [self deleteKeychainDataForKey:key];
}

+ (BOOL)addPassword:(NSString *)pass forKey:(NSString *)key
{
    key = [@"z_key_chain_chenhongxin_pass:" stringByAppendingString:key];
   return  [self addKeychainData:pass forKey:key];
}
+ (NSString *)getPasswordForKey:(NSString *)key
{
    key = [@"z_key_chain_chenhongxin_pass:" stringByAppendingString:key];
    return [self getKeychainDataForKey:key];
}

+ (BOOL)deletePasswordForKey:(NSString *)key{
    key = [@"z_key_chain_chenhongxin_pass:" stringByAppendingString:key];
   return  [self deleteKeychainDataForKey:key];
}
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kSecClassGenericPassword,(id)kSecClass,// 标识符(kSecAttrGeneric通常值位密码)
            service, (__bridge id)kSecAttrService,// 服务(kSecAttrService)
            service, (__bridge id)kSecAttrAccount,// 账户(kSecAttrAccount)
            (__bridge id)kSecAttrAccessibleAfterFirstUnlock,(__bridge id)kSecAttrAccessible,// kSecAttrAccessiblein变量用来指定这个应用何时需要访问这个数据
            nil];
}

+ (BOOL)addKeychainData:(NSString *)data forKey:(NSString *)key
{
    // 获取查询字典
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    // 在删除之前先删除旧数据
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    // 添加新的数据到字典
    data =  [self aes256_encrypt:Z_SECRET_KEY text:data ];
    data = [self aes256_encrypt:Z_SECRET_KEY_TWO text:data];
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    // 将数据字典添加到钥匙串
    OSStatus status =  SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
    ZWLog(@"OSStatus == %d",status);
    if (status == 0) {
        return YES;
    }
    return NO;
}

+ (NSString *)getKeychainDataForKey:(NSString *)key
{
//    key = [@"z_key_chain_chenhongxin:" stringByAppendingString:key];
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            ZWLog(@"Unarchive of %@ failed: %@",key,e);
        } @finally {
            
        }
    }
    
    if (keyData) {
        CFRelease(keyData);
    }
    if (ret) {
       ret = [self aes256_decrypt:Z_SECRET_KEY_TWO text:ret];
       ret = [self aes256_decrypt:Z_SECRET_KEY text:ret];
    }
    return ret;
}
+ (BOOL)deleteKeychainDataForKey:(NSString *)key
{
//    key = [@"z_key_chain_chenhongxin:" stringByAppendingString:key];
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    OSStatus status =  SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    ZWLog(@"delete OSStatus%d",status);
    if (status == 0) {
        return YES;
    }
    return NO;
}














//+ (NSString *)encode:(NSString *)text
//{
//    return [self aes256_encrypt:Z_SECRET_KEY text:text];
//}
//+ (NSString *)decode:(NSString *)text{
//    return [self aes256_decrypt:Z_SECRET_KEY text:text];
//}
// 加密
+ (NSString *)aes256_encrypt:(NSString *)key text:(NSString *)text{
    
    const char *cstr = [text cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:text.length];
    //对数据进行加密
    NSData *result = [self aes256_encrypt:key data:data];
    //转换为2进制字符串
    if (result && result.length > 0) {
        Byte *datas = (Byte*)[result bytes];
        NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
        for(int i = 0; i < result.length; i++){
            [output appendFormat:@"%02x", datas[i]];
        }
        return output;
    }
    return nil;
}


// 解密
+(NSString *)aes256_decrypt:(NSString *)key text:(NSString *)text{
    
    //转换为2进制Data
    NSMutableData *data = [NSMutableData dataWithCapacity:text.length / 2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [text length] / 2; i++) {
        byte_chars[0] = [text characterAtIndex:i*2];
        byte_chars[1] = [text characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    
    //对数据进行解密
    NSData* result = [self aes256_decrypt:key data:data];
    if (result && result.length > 0) {
        
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    return nil;
}







// 加密
+ (NSData *)aes256_encrypt:(NSString *)key data:(NSData *)data{
    
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
  
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [data bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    return nil;
}
// 解密
+ (NSData *)aes256_decrypt:(NSString *)key data:(NSData *)data{
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        
    }
    free(buffer);
    return nil;
}





@end
